package top.hekun.study.reptile.model;

import lombok.Getter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

/**
 * 直接缓冲区代理
 *
 * @Author: 贺坤
 * @Date: 2023/4/23 15:14
 */
public class ByteBufferProxy {
    /**
     * 缓冲区
     */
    @Getter
    private ByteBuffer byteBuffer;

    /**
     * 获取缓冲器代理
     * @param byteBuffer
     */
    public ByteBufferProxy(ByteBuffer byteBuffer) {
        this.byteBuffer = byteBuffer;
    }

    /**
     * 设置写出模式
     * @return
     */
    public ByteBufferProxy flip() {
        this.byteBuffer.flip();
        return this;
    }

    /**
     * 设置写入模式
     * @return
     */
    public ByteBufferProxy compact() {
        this.byteBuffer.compact();
        return this;
    }

    /**
     * 写入字符串
     * @param src
     * @return
     */
    public ByteBufferProxy write(String src) {
        byteBuffer.put(src.getBytes(StandardCharsets.UTF_8));
        return this;
    }

    /**
     * 向管道从写入 channel
     * @param channel
     * @return
     */
    public ByteBufferProxy writeChannel(FileChannel channel) throws IOException {
        flip();
        channel.write(getByteBuffer());
        return this;
    }


}
